package com.yricky.indesk.viewmodel

import android.text.format.DateFormat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yricky.indesk.app
import com.yricky.indesk.model.pojo.DesktopConfig
import com.yricky.indesk.utils.removeItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @author Yricky
 * @date 2021/12/26
 */
class MainActivityViewModel:ViewModel() {
    data class ViewState(
        val config: DesktopConfig = DesktopConfig(5,5, emptyList()),
        val index:Int = 0,
        val bottomBarText:String = ""
    )
    private val _viewState: MutableStateFlow<ViewState> = MutableStateFlow(ViewState())
    val viewState = _viewState.asStateFlow()

    sealed class Action{
        object QueryConfig:Action()
        class FlipTo(val index: Int):Action()
        class RemoveEntrance(val index:Int):Action()
        class SetBottomText(val txt:String):Action()
    }
    val flipP get() = Action.FlipTo(
        with(_viewState.value){
            if(index == 0)
                config.pages.size-1
            else index - 1
        }
    )
    val flipN get() = Action.FlipTo(
        with(_viewState.value){
            if(index == config.pages.size-1)
                0
            else index + 1
        }
    )

    fun onAction(action:Action){
        when(action){
            is Action.QueryConfig -> {
                viewModelScope.launch {
                    withContext(Dispatchers.IO){
                        val dCfg = app.appConfig.desktopConfig
                        _viewState.value = _viewState.value.copy(
                            config = dCfg,
                            index = _viewState.value.index.coerceIn(0,dCfg.pages.size-1)
                        )
                    }
                }
            }
            is Action.FlipTo -> {
                _viewState.value = _viewState.value.copy(
                    index = action.index
                )
            }
            is Action.RemoveEntrance->{
                app.appConfig.desktopConfig =
                    app.appConfig.desktopConfig.removeItem(
                        _viewState.value.index,
                        action.index
                    )
            }
            is Action.SetBottomText ->{
                _viewState.value = _viewState.value.copy(
                    bottomBarText = action.txt
                )
            }
        }
    }
}